package com.antler.smt.admin.config;

import com.antler.smt.admin.mapper.SysLogEntityMapper;
import com.antler.smt.admin.mapper.UserEntityMapper;
import com.antler.smt.admin.utils.ShiroUtils;
import com.antler.smt.entity.SysLogEntity;
import com.antler.smt.entity.UserEntity;
import com.antler.smt.utils.DateUtil;
import com.antler.smt.utils.LogUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.antler.smt.admin.annotation.OperateCut;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Optional;

/**
 *  注解拦截
 *
 * @author zhangyi
 * @date 2018/6/15 16:53
 */
@Aspect
@Order(-99)
@Component
public class AopConfig {
    /**
     * 日志
     */
    private static Logger log = LogUtil.get();

    @Autowired
    private UserEntityMapper userEntityMapper;

    @Autowired
    private SysLogEntityMapper sysLogEntityMapper;

    /**
     * 专员操作内容
     */
    private StringBuffer content;

    @Pointcut("@annotation(com.antler.smt.admin.annotation.OperateCut)")
    public void operate(){}

    @After("operate()")
    public void afterOperate(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        OperateCut annotation = method.getAnnotation(OperateCut.class);
        content = new StringBuffer(annotation.content());
        log.info("后台拦截注解:"+annotation.content());
    }
    /**
     * 定义切点
     */
    @Pointcut("execution(* com.antler.smt.admin.controller..*.*(..))")
    public void operateCut(){}

    @AfterReturning(pointcut = "operateCut()",returning = "returning")
    public void afterRetuing(JoinPoint joinPoint,Object returning){
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest();
        if(returning != null && content != null){
            //创建系统日志实体
            SysLogEntity sysLogEntity = new SysLogEntity();
            //调用的方法
            String methodName = joinPoint.getSignature().getName();
            //获取用户请求的参数
            String params = Arrays.toString(joinPoint.getArgs());
            //当前用户的ip地址
            String localIp = getLocalIp(request);
            //获取当前项目专员信息
            String realName = null;
            if(UserEntity.class instanceof Object){
                UserEntity user = (UserEntity) ShiroUtils.getSubject().getPrincipal();
                Long id = new Long(0);
                if(null != user) {
                   id  = user.getId();
                }
                UserEntity userEntity = userEntityMapper.selectByPrimaryKey(id);
                boolean present = Optional.ofNullable(userEntity).isPresent();
                //获取项目专员真实姓名
                realName = present?userEntity.getRealName():"未知用户IP:"+request.getLocalAddr();
            }
            String content = this.content.toString();
            sysLogEntity.setIp(localIp);
            sysLogEntity.setUserName(realName);
            sysLogEntity.setOperationContent(content);
            sysLogEntity.setParams(params);
            sysLogEntity.setMethod(methodName);
            sysLogEntity.setCreateTime(DateUtil.stampToDate(System.currentTimeMillis()));
            sysLogEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));
            if(null != sysLogEntity.getOperationContent()  && !"".equals(sysLogEntity.getOperationContent())) {
                sysLogEntityMapper.insertSelective(sysLogEntity);
            }
            this.content.delete(0,content.length());
        }
    }



    /**
     * 获取当前请求的IP地址
     *
     * @param request
     * @return
     */
    public static String getLocalIp(HttpServletRequest request) {

        String ip="";
        if (request.getHeader("x-forwarded-for") == null) {
            ip = request.getRemoteAddr();
        }else{
            ip = request.getHeader("x-forwarded-for");
        }
        if(ip.length()>15){
            if(ip.indexOf(",")>0){
                ip = ip.substring(0,ip.indexOf(","));
            }
        }
        return ip;
    }
}
